package com.phoenix;

import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy;
import com.dangdang.ddframe.rdb.sharding.jdbc.ShardingDataSource;
import com.google.common.collect.Maps;
import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by lilongfei on 16/10/9.
 */
@Configuration
public class DemoConfig {

    BasicDataSource dataSource(){
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://172.16.232.131:3306/testdb");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    @Bean(name = "shardingDataSource",destroyMethod = "shutdown")
    ShardingDataSource shardingDataSource(){

        Map<String,DataSource> dataSourceMap = Maps.newHashMap();
        dataSourceMap.put("testdb",dataSource());
        DataSourceRule dataSourceRule = new DataSourceRule(dataSourceMap);
        TableRule tableRule = TableRule.builder("t_info").actualTables(Arrays.asList("t_info_1","t_info_0"))
                .dataSourceRule(dataSourceRule)
                .tableShardingStrategy(new TableShardingStrategy("user_id",new SingleKeyModuleTableShardingAlgorithm()))
                .build();
        ShardingRule shardingRule = ShardingRule.builder()
                .dataSourceRule(dataSourceRule)
                .tableRules(Arrays.asList(tableRule)).build();
        ShardingDataSource shardingDataSource = new ShardingDataSource(shardingRule);
        return shardingDataSource;
    }

    @Bean(name = "sqlSessionFactoryBean")
    @Primary
    SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("shardingDataSource") ShardingDataSource dataSource){

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean
    MapperScannerConfigurer mapperScannerConfigurer(){

        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.phoenix");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return mapperScannerConfigurer;
    }

}
